package org.ehe.erp.service.quality.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.bom.domain.BomMaster;
import org.ehe.business.bom.service.BomMasterService;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.erp.domain.quality.ErpBomQualityItem;
import org.ehe.erp.domain.quality.ErpQualityItem;
import org.ehe.erp.domain.quality.bo.ErpBomQualityItemBo;
import org.ehe.erp.domain.quality.vo.ErpBomQualityItemVo;
import org.ehe.erp.mapper.quality.ErpBomQualityItemMapper;
import org.ehe.erp.service.quality.ErpBomQualityItemService;
import org.ehe.erp.service.quality.ErpQualityItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * BOM质检项目关联视图ServiceImpl
 * @author :zhangnn
 * @className :ErpBomQualityItemServiceImpl
 * @description: TODO
 * @date 2025-09-10 16:32:18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErpBomQualityItemServiceImpl extends ServiceImpl<ErpBomQualityItemMapper, ErpBomQualityItem> implements ErpBomQualityItemService {
    private final ErpBomQualityItemMapper bomQualityItemMapper;
    private final ErpQualityItemService qualityItemService;
    private final BomMasterService bomMasterService;

    /**
     * 分页列表
     * @param bo 查询条件
     * @param pageQuery 分页参数
     * @return
     */
    @Override
    public TableDataInfo<ErpBomQualityItemVo> queryPageList(ErpBomQualityItemBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpBomQualityItem> lqw = new LambdaQueryWrapper<>();
        lqw.eq(null != bo.getBomId(),ErpBomQualityItem::getBomId,bo.getBomId());
        lqw.eq(null != bo.getQualityItemId(),ErpBomQualityItem::getQualityItemId,bo.getQualityItemId());
        IPage<ErpBomQualityItemVo> erpBomQualityItemVoIPage = baseMapper.selectVoPage(pageQuery.build(), lqw);
        erpBomQualityItemVoIPage.getRecords().forEach(p->{
            Long qualityItemId = p.getQualityItemId();
            ErpQualityItem item = qualityItemService.getById(qualityItemId);
            if(Objects.nonNull(item)){
                p.setItemCode(item.getItemCode());
                p.setItemName(item.getItemName());
                p.setCategory(item.getCategory());
                p.setCheckMethod(item.getCheckMethod());
                p.setStandard(item.getStandard());
            }
            BomMaster bom = bomMasterService.getById(p.getBomId());
            if(Objects.nonNull(bom)){
                p.setBomCode(bom.getBomCode());
                p.setBomName(bom.getBomName());
            }
        });
        return TableDataInfo.build(erpBomQualityItemVoIPage);
    }

    /**
     * 查询BOM质检项目关联列表
     * @param bo 查询条件
     * @return
     */
    @Override
    public List<ErpBomQualityItemVo> queryList(ErpBomQualityItemBo bo) {
        return bomQualityItemMapper.selectBomQualityItemList(bo);
    }

    /**
     * 根据ID查询BOM质检项目关联详情
     * @param id BOM质检项目关联ID
     * @return
     */
    @Override
    public ErpBomQualityItemVo queryById(Long id) {
        return bomQualityItemMapper.selectBomQualityItemVoById(id);
    }

    /**
     * 保存
     * @param bos BOM质检项目关联信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(List<ErpBomQualityItemBo> bos) {
        for (ErpBomQualityItemBo bo : bos) {
            // 校验质检项目是否存在且启用
            validateQualityItem(bo.getQualityItemId());

            // 校验关联关系是否已存在
            if (checkRelationExists(bo.getBomId(), bo.getQualityItemId())) {
                throw new RuntimeException(bo.getBomId()+"-"+bo.getQualityItemId()+"质检项目的关联关系已存在");
            }

            ErpBomQualityItem add = BeanUtil.toBean(bo, ErpBomQualityItem.class);
            validEntityBeforeSave(add);
            boolean flag = bomQualityItemMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
        }
        return true;
    }

    /**
     * 修改
     * @param bo BOM质检项目关联信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ErpBomQualityItemBo bo) {
        // 校验质检项目是否存在且启用
        validateQualityItem(bo.getQualityItemId());

        ErpBomQualityItem update = BeanUtil.toBean(bo, ErpBomQualityItem.class);
        validEntityBeforeSave(update);
        return bomQualityItemMapper.updateById(update) > 0;
    }

    /**
     * 根据ID删除
     * @param ids 主键集合
     * @param isValid 是否校验
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以在这里添加删除前的业务校验逻辑
        }
        return bomQualityItemMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取bom下物料
     * @param bomId BOM ID
     * @return
     */
    @Override
    public List<ErpBomQualityItemVo> getQualityItemsByBomId(Long bomId) {

        return bomQualityItemMapper.selectQualityItemsByBomId(bomId);
    }

    /**
     *  根据质检项目ID查询关联的BOM列表
     * @param qualityItemId 质检项目ID
     * @return
     */
    @Override
    public List<ErpBomQualityItemVo> getBomsByQualityItemId(Long qualityItemId) {
        return bomQualityItemMapper.selectBomsByQualityItemId(qualityItemId);
    }

    /**
     * 为BOM批量设置质检项目
     * @param bomId BOM ID
     * @param qualityItemIds 质检项目ID列表
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setBomQualityItems(Long bomId, List<Long> qualityItemIds) {
        // 先删除原有关联关系
        deleteByBomId(bomId);

        if (qualityItemIds == null || qualityItemIds.isEmpty()) {
            return true;
        }

        // 批量新增关联关系
        List<ErpBomQualityItem> relations = qualityItemIds.stream()
            .map(qualityItemId -> {
                ErpBomQualityItem relation = new ErpBomQualityItem();
                relation.setBomId(bomId);
                relation.setQualityItemId(qualityItemId);
                relation.setIsRequired(1); // 默认必检
                relation.setSort(0);
                return relation;
            })
            .collect(Collectors.toList());

        return bomQualityItemMapper.insertBatch(relations);
    }

    /**
     * 为BOM批量设置质检项目（带必检标识）
     * @param bomId BOM ID
     * @param qualityItems 质检项目配置列表
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setBomQualityItemsWithConfig(Long bomId, List<ErpBomQualityItemBo> qualityItems) {
        // 先删除原有关联关系
        deleteByBomId(bomId);

        if (qualityItems == null || qualityItems.isEmpty()) {
            return true;
        }

        // 批量新增关联关系（带配置）
        List<ErpBomQualityItem> relations = qualityItems.stream()
            .map(bo -> {
                // 校验质检项目是否存在且启用
                validateQualityItem(bo.getQualityItemId());

                ErpBomQualityItem relation = BeanUtil.toBean(bo, ErpBomQualityItem.class);
                relation.setBomId(bomId);
                validEntityBeforeSave(relation);
                return relation;
            })
            .collect(Collectors.toList());

        return bomQualityItemMapper.insertBatch(relations);
    }

    /**
     * 根据BOM ID删除关联关系
     * @param bomId BOM ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByBomId(Long bomId) {
        return bomQualityItemMapper.deleteById(bomId) >= 0;
    }

    /**
     * 根据质检项目ID删除关联关系
     * @param qualityItemId 质检项目ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByQualityItemId(Long qualityItemId) {
        return baseMapper.deleteByQualityItemId(qualityItemId) >= 0;
    }

    /**
     * 校验BOM和质检项目关联是否存在
     * @param bomId BOM ID
     * @param qualityItemId 质检项目ID
     * @return
     */
    @Override
    public Boolean checkRelationExists(Long bomId, Long qualityItemId) {
        LambdaQueryWrapper<ErpBomQualityItem> wrapper = Wrappers.<ErpBomQualityItem>lambdaQuery()
            .eq(ErpBomQualityItem::getBomId, bomId)
            .eq(ErpBomQualityItem::getQualityItemId, qualityItemId);
        return baseMapper.selectCount(wrapper) > 0;
    }

    /**
     * 复制BOM的质检项目关联到另一个BOM
     * @param sourceBomId 源BOM ID
     * @param targetBomId 目标BOM ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyBomQualityItems(Long sourceBomId, Long targetBomId) {
        // 获取源BOM的质检项目关联
        List<ErpBomQualityItemVo> sourceRelations = getQualityItemsByBomId(sourceBomId);

        if (sourceRelations.isEmpty()) {
            return true;
        }

        // 先删除目标BOM的原有关联关系
        deleteByBomId(targetBomId);

        // 复制关联关系
        List<ErpBomQualityItem> targetRelations = sourceRelations.stream()
            .map(sourceVo -> {
                ErpBomQualityItem relation = new ErpBomQualityItem();
                relation.setBomId(targetBomId);
                relation.setQualityItemId(sourceVo.getQualityItemId());
                relation.setIsRequired(sourceVo.getIsRequired());
                relation.setSort(sourceVo.getSort());
                return relation;
            })
            .collect(Collectors.toList());

        return baseMapper.insertBatch(targetRelations);
    }

    /**
     * 校验质检项目是否存在且启用
     */
    private void validateQualityItem(Long qualityItemId) {
        ErpQualityItem qualityItem = qualityItemService.getById(qualityItemId);
        if (qualityItem == null) {
            throw new RuntimeException("质检项目不存在");
        }
        if (qualityItem.getStatus() == null || qualityItem.getStatus() != 1) {
            throw new RuntimeException("质检项目已禁用，无法关联");
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpBomQualityItem entity) {
        if (ObjectUtil.isNull(entity.getIsRequired())) {
            entity.setIsRequired(1);
        }
        if (ObjectUtil.isNull(entity.getSort())) {
            entity.setSort(0);
        }
    }
}
